package studentmsg

import "fmt"

// standardTitle is used to print a standard title for message printing
func standardTitle() {
	fmt.Printf("编号\t姓名\t学号\t\t语文成绩\t数学成绩\t英语成绩\t总成绩\n")
}

// standardPrint is used to print a standard line to show student's message
func standardPrint(key int, name string, id string, chineseGrades int, mathGrades int, englishGrades int) {
	fmt.Printf(
		"%d\t%s\t%s\t%d\t\t%d\t\t%d\t\t%d\n",
		key, name, id,
		chineseGrades, mathGrades, englishGrades,
		chineseGrades+mathGrades+englishGrades,
	)
}

// GetAllStudnets is used to get all students' message from MsgList and print in screen
func GetAllStudnets(l *MsgList) {
	students := l.getAll()
	averageOfChineseGrades := 0
	averageOfMathGrades := 0
	averageOfEnglishGrades := 0
	standardTitle()
	for key, value := range students {
		standardPrint(
			key, value.name, value.id,
			value.chineseGrades, value.mathGrades, value.englishGrades,
		)
		averageOfChineseGrades += value.chineseGrades
		averageOfMathGrades += value.mathGrades
		averageOfEnglishGrades += value.englishGrades
	}
	if l.length != 0 {
		averageOfChineseGrades = averageOfChineseGrades / l.length
		averageOfMathGrades = averageOfMathGrades / l.length
		averageOfEnglishGrades = averageOfEnglishGrades / l.length
	} else {
		averageOfChineseGrades = 0
		averageOfMathGrades = 0
		averageOfEnglishGrades = 0
	}
	fmt.Printf(
		"平均分:\t\t\t\t%d\t\t%d\t\t%d\n",
		averageOfChineseGrades,
		averageOfMathGrades,
		averageOfEnglishGrades,
	)
}

// SearchStudents is used to search student's message base on name and id
func SearchStudents(l *MsgList, name string, id string) {
	studentsIndex, err := l.search(name, id)
	if err != nil {
		fmt.Println(err)
		return
	}
	standardTitle()
	for key, value := range studentsIndex {
		student := l.getStudent(value)
		standardPrint(
			key, student.name, student.id,
			student.chineseGrades, student.mathGrades, student.englishGrades,
		)
	}
}

// AddStudent is used to add a student into MsgList
func AddStudent(l *MsgList, student *StudentMsg) bool {
	newStudent := student.copy()
	return l.insert(l.length, newStudent)
}

// DeleteStudent is used to delete a student message from MsgList
func DeleteStudent(l *MsgList, index int) bool {
	result := l.delete(index)
	if result == nil {
		return false
	}
	return true
}
